from django.shortcuts import render,HttpResponse
from user.models import User
# Create your views here.
def index_handler(request):
    users = User.objects.all()
    return render(request,'index.html',context={'users':users})

def add_handler(request):
    if request.method == 'GET':
        return render(request,'add.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        age = request.POST.get('age')
        email = request.POST.get('email')
        try:
            User(username=username, password=password, age=age,email=email).save()
            return render(request, 'result.html', {'message': '新增用户成功'})
        except:
            return render(request, 'result.html', {'message': '新增用户失败'})


def alter_handler(request,id):
    user = User.objects.get(id=id)
    if request.method == 'GET':
        return render(request,'alter.html',context={'user':user})
    else:
        user.username = request.POST.get('username')
        user.password = request.POST.get('password')
        user.age = request.POST.get('age')
        user.email = request.POST.get('email')
    try:
        user.save()
        return render(request,'result.html',context={'message':'修改用户成功'})
    except:
        return render(request, 'result.html', context={'message': '修改用户失败'})


def del_handler(request,id):
    try:
        User.objects.get(id=id).delete()
        return render(request,'result.html',context={'message':'删除用户成功'})
    except:
        return render(request, 'result.html', context={'message': '删除用户失败'})